package com.aw.guiguzi.module.common

import android.os.SystemClock
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import com.aw.baselib.base.AwMvpBindingActivity
import com.aw.baselib.constants.Extras
import com.aw.baselib.util.AwAppUtils
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwJsonUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.AwSoftKeyboardUtil
import com.aw.baselib.util.AwVersionUtil
import com.aw.baselib.util.AwViewUtil
import com.aw.baselib.util.update.AwUpdateUtil
import com.aw.baselib.util.update.UpdateBean
import com.aw.guiguzi.R
import com.aw.guiguzi.bean.PGYUpdateBean
import com.aw.guiguzi.databinding.ActivityLoginBinding
import com.aw.guiguzi.module.common.presenters.LoginPresent
import com.aw.guiguzi.module.common.views.LoginView
import com.aw.guiguzi.util.AppUserUtil.account
import com.aw.guiguzi.util.AppUserUtil.token
import com.pgyersdk.update.PgyUpdateManager
import com.pgyersdk.update.UpdateManagerListener

class LoginActivity : AwMvpBindingActivity<LoginPresent?, ActivityLoginBinding?>(), LoginView.View {

    private var isOpenEye : Boolean = false;
    private var mHits = LongArray(5)

    override fun getViewBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(mActivity.layoutInflater)
    }

    override fun createPresenter(): LoginPresent? {
        return LoginPresent(this);
    }

    override fun initView() {
        super.initView()
        var etList = arrayListOf<EditText>()
        /**
         * binding?.let
         * 如果 binding 不为 null，调用 let 函数; 如果 binding 为 null，整个表达式返回 null,
         * 等价于 if (binding != null) { val it = binding ...后续代码块 }
         */
        binding?.let {
            // 在这个 lambda 中，it 指向 binding（非空）
            etList.add(it.etPhone)
            etList.add(it.etPwd)
            AwViewUtil.setEnableView(etList, it.etPhone, it.tvLogin)
            AwViewUtil.setEnableView(etList, it.etPwd, it.tvLogin)
        }

    }

    override fun initData() {
        super.initData()
        binding!!.etPwd.transformationMethod = PasswordTransformationMethod.getInstance()
        setText(binding!!.tvVersion, "当前版本 ${AwVersionUtil.getVersion(mActivity)}")
        if (!AwDataUtil.isEmpty(account)) {
            setText(binding!!.etPhone, account)
        }
        if (intent != null && !AwDataUtil.isEmpty(intent.getStringExtra(Extras.params)) && intent.getStringExtra(
                Extras.params
            ) == "ReLogin"
        ) {
            showDialog("令牌已过期或失效，请重新登录")
        }
        if (!AwDataUtil.isEmpty(token)) {
            toClass(MainActivity::class.java, true)
        } else {
            checkAppUpdate(true)
        }
    }

    override fun initListener() {
        super.initListener()
        binding?.let {
            it.tvVersion.setOnClickListener { checkAppUpdate(false) }
            it.tvToPhoneCode.setOnClickListener { mActivity.finish() }
            it.tvToForget.setOnClickListener { showToDevMsg() }
            it.ivEye.setOnClickListener {
                if (isOpenEye) {
                    binding!!.ivEye.setImageResource(R.drawable.icon_eye_off)
                    isOpenEye = false
                    binding!!.etPwd.transformationMethod = PasswordTransformationMethod.getInstance()
                } else {
                    binding!!.ivEye.setImageResource(R.drawable.icon_eye_on)
                    isOpenEye = true
                    binding!!.etPwd.transformationMethod = HideReturnsTransformationMethod.getInstance()
                }
                binding!!.etPwd.setSelection(getText(binding!!.etPwd).length)
            }
            it.tvLogin.setOnClickListener {
                if (AwDataUtil.isEmpty(getText(binding!!.etPhone))) {
                    showMsg("请输入账号")
                    return@setOnClickListener
                }
                if (AwDataUtil.isEmpty(getText(binding!!.etPwd))) {
                    showMsg("请输入密码")
                    return@setOnClickListener
                }
                mPresenter?.login(getText(binding!!.etPhone), getText(binding!!.etPwd))
            }
        }
    }

    override fun onBackPressed() {
//        AwThirdAppJudgeUtil.toDesktop(mActivity);
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - 2000) {
            finish()
            ExitAppForced()
        } else {
            showMsg("再次点击返回键退出应用")
        }
    }

    private fun checkAppUpdate(isInitCheck: Boolean) {
        PgyUpdateManager.register(mActivity, object : UpdateManagerListener() {
            override fun onUpdateAvailable(s: String) {
                AwLog.d("Update onUpdateAvailable: $s")
                val pgyUpdateBean: PGYUpdateBean = AwJsonUtil.getInstance().fromJson(
                    s,
                    PGYUpdateBean::class.java
                ) as PGYUpdateBean
                if (pgyUpdateBean.data != null) {
                    val currentVersion = AwAppUtils.getAppVersionInfo(
                        mActivity,
                        AwAppUtils.TYPE_VERSION.TYPE_VERSION_NAME
                    )
                    var compareVerson = if (pgyUpdateBean.data?.isNeedForceUpdate == true) {
                        pgyUpdateBean.data?.forceUpdateVersion
                    } else {
                        pgyUpdateBean.data?.versionName
                    }
                    if (AwVersionUtil.compareVersions(currentVersion, compareVerson) > 0) {
                        val updateBean = UpdateBean()
                        updateBean.appurl = pgyUpdateBean.data?.downloadURL
                        updateBean.isForceRenew = if (pgyUpdateBean.data?.isNeedForceUpdate == true) "1" else "0"
                        updateBean.description = pgyUpdateBean.data?.releaseNote
                        updateBean.appVersion = pgyUpdateBean.data?.versionName
                        AwUpdateUtil.getInstance(mActivity).handleUpdate(
                            updateBean
                        ) {}
                    } else {
                        if (isInitCheck) {
                            return
                        }
                        showMsg("已是最新版")
                    }
                } else {
                    if (isInitCheck) {
                        return
                    }
                    showMsg("已是最新版")
                }
            }

            override fun onNoUpdateAvailable() {
                AwLog.d("Update 已是最新版")
                if (isInitCheck) {
                    return
                }
                showMsg("已是最新版")
            }
        })
    }

    override fun onDestroy() {
        AwSoftKeyboardUtil.hideSoftKeyboard(mActivity)
        super.onDestroy()
    }

    override fun loginHandleSuccess() {
        showMsg("登录成功")
        toClass(MainActivity::class.java, true)
    }
}